import React, { useCallback, useEffect, useRef, useState } from 'react';
import { Form, Input, Button, Card, Tag, Spin, message } from 'antd';
import { SearchOutlined } from '@ant-design/icons';
import { history } from '@umijs/max';
import { CelebrityStageCutInfo, getCelebrityStageCutInfoPage } from '@/services/CelebrityStageCutInfo';
import { famousPersonId } from '@/services/index';
import styles from './index.less';

const StageList: React.FC = () => {
  const [form] = Form.useForm();
  const [data, setData] = useState<CelebrityStageCutInfo[]>([]);
  const [loading, setLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [total, setTotal] = useState(0);
  const [hasMore, setHasMore] = useState(true);
  const containerRef = useRef<HTMLDivElement>(null);
  const loadingRef = useRef(false);

  // 获取数据
  const fetchData = async (values: any, page: number = 1, append: boolean = false) => {
    if (loadingRef.current) return;
    loadingRef.current = true;
    
    try {
      setLoading(true);
      const response = await getCelebrityStageCutInfoPage({
        ...values,
        pageCurrent: page,
        pageSize: 12,
        famousPersonId: famousPersonId
      });

      if (response) {
        const { list, totalCount } = response;
        setTotal(totalCount);
        setHasMore(list.length > 0 && (page - 1) * 12 + list.length < totalCount);
        
        if (append) {
          setData(prev => [...prev, ...list]);
        } else {
          setData(list);
          setCurrentPage(1);
        }
        
        if (!append) {
          containerRef.current?.scrollTo(0, 0);
        }
      }
    } catch (error) {
      message.error('获取舞台列表失败');
    } finally {
      setLoading(false);
      loadingRef.current = false;
    }
  };

  // 处理搜索
  const handleSearch = (values: any) => {
    fetchData(values);
  };

  // 处理重置
  const handleReset = () => {
    form.resetFields();
    fetchData({});
  };

  // 处理滚动加载
  const handleScroll = useCallback(() => {
    if (!containerRef.current || loading || !hasMore || loadingRef.current) return;

    const container = containerRef.current;
    const { scrollTop, clientHeight, scrollHeight } = container;

    if (scrollHeight - scrollTop - clientHeight < 100) {
      const values = form.getFieldsValue();
      fetchData(values, currentPage + 1, true);
      setCurrentPage(prev => prev + 1);
    }
  }, [loading, hasMore, currentPage, form]);

  useEffect(() => {
    const container = containerRef.current;
    if (container) {
      container.addEventListener('scroll', handleScroll);
      return () => container.removeEventListener('scroll', handleScroll);
    }
  }, [handleScroll]);

  // 初始加载
  useEffect(() => {
    fetchData({});
  }, []);

  // 处理卡片点击
  const handleCardClick = (id: number) => {
    history.push(`/works/stage/${btoa(id.toString())}`);
  };

  return (
    <div className={styles.stageListContent}>
      <div className={styles.searchSection}>
        <Form
          form={form}
          onFinish={handleSearch}
          className={styles.searchForm}
        >
          <Form.Item name="keyword" className={styles.searchInput}>
            <Input
              placeholder="搜索舞台名称、活动、描述..."
              allowClear
              size="middle"
              prefix={<SearchOutlined style={{ color: '#bfbfbf' }} />}
            />
          </Form.Item>
          <div className="button-group">
            <Button type="primary" htmlType="submit" size="middle">搜索</Button>
            <Button onClick={handleReset} size="middle">重置</Button>
          </div>
        </Form>
        <div className={styles.searchResult}>
          找到 <span>{total}</span> 个舞台作品
        </div>
      </div>

      <div className={styles.stageListWrapper} ref={containerRef}>
        <div className={styles.stageList}>
          {data.map((item) => (
            <Card
              key={item.id}
              className={styles.stageCard}
              onClick={() => item.id && handleCardClick(item.id)}
            >
              <div className={styles.posterWrapper}>
                {item.thumbnailId && (
                  <img
                    src={`/api/file/play/${item.thumbnailId}`}
                    alt={item.stageName}
                    className={styles.poster}
                  />
                )}
              </div>
              <div className={styles.contentWrapper}>
                <div className={styles.header}>
                  <h3 className={styles.title}>{item.stageName}</h3>
                </div>
                <div className={styles.infoList}>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>标签：</span>
                    <span className={styles.value}>
                      {item.tags.split(/[,，、]/g).map((tag, index) => (
                        <Tag key={index} color="blue">{tag.trim()}</Tag>
                      ))}
                    </span>
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>来源：</span>
                    <span className={styles.value}>
                      <Tag color="blue">{item.cr}</Tag>
                    </span>
                  </div>
                  <div className={styles.infoItem}>
                    <span className={styles.label}>时间：</span>
                    <span className={styles.value}>{item.uploadDate}</span>
                  </div>
                  {item.description && (
                    <div className={styles.infoItem}>
                      <span className={styles.label}>描述：</span>
                      <div className={styles.description}>{item.description}</div>
                    </div>
                  )}
                </div>
              </div>
            </Card>
          ))}
        </div>
        
        {loading && (
          <div className={styles.loadingMore}>
            <Spin />
            <span>加载中...</span>
          </div>
        )}
        
        {!hasMore && data.length > 0 && (
          <div className={styles.noMore}>
            没有更多数据了
          </div>
        )}
      </div>
    </div>
  );
};

export default StageList; 